<template>
  <article class="event-search">
    <el-input v-model.trim="keyword" placeholder="请输入事件类型"></el-input>
    <el-button @click="handleQuery">{{ isSearching ? '停止' : '' }}查询</el-button>
    <SelectEventFeature :queryResultLayer :map v-model="canSelect" />
  </article>
</template>

<script setup>
import { ref, watch } from 'vue'
import SelectEventFeature from './SelectEventFeature.vue'
import locationIcon from '@/assets/icons/location.svg'

const { map } = defineProps({
  map: {
    type: Object,
    required: true,
  },
})

const isSearching = ref(false)
const canSelect = ref(false)
const keyword = ref('')

// 初始化查询结果图层
const queryResultLayer = new ol.layer.Vector({})
const queryResultSource = new ol.source.Vector({ wrapX: false })
queryResultLayer.setSource(queryResultSource)
map.addLayer(queryResultLayer)

// 封装查询功能
const queryEvent = (keyword) => {
  // 调用封装的函数清除查询结果图层
  clearA()

  // 设置查询结构
  const queryStruct = new Zondy.Service.QueryFeatureStruct({
    IncludeGeometry: true, //是否包含几何图形信息
  })

  // 查询参数信息对象
  const queryParam = new Zondy.Service.QueryByLayerParameter(
    'gdbp://MapGisLocal/wuhan/sfcls/事件',
    {
      struct: queryStruct,
      recordNumber: 10000, //查询记录数
      where: `事件类型 like '%${keyword}%'`, //查询条件SQL语句
    },
  )
  // 实例化矢量图层查询服务对象
  const queryService = new Zondy.Service.QueryLayerFeature(queryParam, {
    ip: '127.0.0.1',
    port: '8089',
  })

  // 执行查询服务对象的查询方法,参数为两个回调函数,成功和失败
  queryService.query(querySuccess, queryError)
}
// 查询成功回调函数
const querySuccess = (result) => {
  // 初始化Zondy.Format.PolygonJSON类
  const format = new Zondy.Format.PolygonJSON()
  // 将MapGIS要素JSON反序列化为ol.Feature类型数组
  const features = format.read(result)
  // 将features添加到查询结果图层
  queryResultSource.addFeatures(features)
  // 样式
  const style = new ol.style.Style({
    image: new ol.style.Icon({
      src: locationIcon,
      anchor: [0.5, 1],
      scale: 0.2,
    }),
  })
  queryResultLayer.setStyle(style)

  canSelect.value = true // 打开选中事件功能
}
// 查询失败回调函数
const queryError = (error) => {
  console.log(error)
}
// 清除查询结果图层
const clearA = () => {
  queryResultSource.clear() // 清除查询结果图层
  canSelect.value = false // 关闭选中事件
}

const handleQuery = () => {
  if (!keyword.value) return // 关键字为空则不查询
  clearA() // 清除查询结果图层
  isSearching.value = !isSearching.value
}

watch(isSearching, (newVal) => {
  if (newVal) {
    queryEvent(keyword.value) // 查询事件
  } else {
  }
})
</script>

<style lang="scss" scoped>
.event-search {
  display: flex;
  align-items: center;
}
</style>
